<template>
  <div class="api-debug ">

    <h3 class="api-title" style="margin-bottom:15px">接口信息</h3>
    <div class="api-debug-info">
      <el-form ref="apiForm" label-width="100px">
        <el-row>
          <el-col :span="10">
            <el-form-item required label="接口编号：">
              <span> {{apiForm.id}}</span>
            </el-form-item>
          </el-col>

          <el-col :span="14">
            <el-form-item required label="接口名称：">
              <span> {{apiForm.name}}</span>
            </el-form-item>

          </el-col>
          <el-col :span="24">
            <el-form-item required label="接口路径：">
              <el-tag v-if="apiForm.method == 'GET'">GET</el-tag>
              <el-tag v-else-if="apiForm.method == 'POST'" type="success">POST</el-tag>
              <el-tag v-else-if="apiForm.method == 'DELETE'" type="info">DELETE</el-tag>
              <el-tag v-else-if="apiForm.method == 'PUT'" type="warning">PUT</el-tag>

              <span class="sletter-spacing: 2px;">{{apiForm.path}}</span>

            </el-form-item>

          </el-col>

        </el-row>
      </el-form>

    </div>

    <h3 class="api-title" style="margin-bottom:15px">Request</h3>
    <div class="api-debug-request">
      <el-input placeholder="请输入内容" v-model="apiForm.path" class="input-with-select">
        <el-select v-model="apiForm.protocol" slot="prepend" placeholder="请选择协议" class="api-debug-select">
          <el-option label="http" value="http"></el-option>
          <el-option label="https" value="https"></el-option>
        </el-select>

        <el-select v-model="envList.domain" slot="prepend" placeholder="请选择环境" class="api-debug-select-1">
          <el-option v-for="(item,index) in envList.list" :label="item.host" :value="item.host" :key="index"></el-option>
        </el-select>
        <el-button slot="append" icon="el-icon-caret-right" type="primary" style="background: #17B3A3;" @click="debugApiExecute(apiForm)" :loading="debugLoading">调试</el-button>
      </el-input>
    </div>

    <div class="api-debug-request-params">

      <div class="api-params-type">
        <el-radio-group v-model="apiForm.requestBodyType">
          <el-radio label="form">form</el-radio>
          <el-radio label="json">json</el-radio>
          <el-radio label="file">file</el-radio>
          <el-radio label="row">row</el-radio>
        </el-radio-group>

      </div>

      <div class="api-tab">
        <el-tabs v-model="activeName" class="interface-edit interface-tab-in">
          <el-tab-pane label="请求参数" name="first">
            <div v-if="apiForm.requestBodyType == 'json'">
              <vueJsonEditor></vueJsonEditor>
            </div>

            <div v-else-if="apiForm.requestBodyType == 'form'">
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="addNewParams()">添加</el-button>
              <el-row v-for="(item,index) in apiForm.queryParam" :key="index">
                <el-col :span="5">
                  <el-input placeholder="参数名" v-model="item.name"></el-input>
                </el-col>
                <el-col :span="3">
                  <el-select placeholder="请选择" v-model="item.must">
                    <el-option label="必填" :value=true>
                    </el-option>
                    <el-option label="非必填" :value=false>
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-input placeholder="参数值" v-model="item.value"></el-input>
                </el-col>
                <el-col :span="7">
                  <el-input placeholder="参数描述" v-model="item.remark"></el-input>
                </el-col>
                <el-col :span="3">
                  <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addNewParams()"></el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" circle v-on:click="apiForm.queryParam.splice(index,1)"></el-button>
                </el-col>
              </el-row>
            </div>

          </el-tab-pane>
          <el-tab-pane label="请求Header" name="second">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addNewHeaders()">添加</el-button>
            <el-row v-for="(item,index) in apiForm.requestHeader" :key="index">
              <el-col :span="8">
                <el-input placeholder="参数名" v-model="item.name"></el-input>
              </el-col>

              <el-col :span="12">
                <el-input placeholder="参数值" v-model="item.value"></el-input>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addNewHeaders()"></el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" circle v-on:click="apiForm.requestHeader.splice(index,1)"></el-button>
              </el-col>
            </el-row>

          </el-tab-pane>
          <el-tab-pane label="请求Cookie" name="third">
            <el-button type="primary" size="mini" icon="el-icon-plus">添加</el-button>
            <el-row>
              <el-col :span="8">
                <el-input placeholder="参数名"></el-input>
              </el-col>
              <el-col :span="12">
                <el-input placeholder="参数值"></el-input>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" size="mini" icon="el-icon-plus" circle></el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" circle></el-button>
              </el-col>
            </el-row>

          </el-tab-pane>
        </el-tabs>

      </div>

    </div>

    <h3 class="api-title" style="margin-bottom:15px;margin-top:20px">Response</h3>
    <div class="api-debug-response">

      <el-tabs v-model="activeResponseName">
        <el-tab-pane label="请求信息" name="first">
          <myEditor v-model="request.url" language='dockerfile' title="response"> </myEditor>

        </el-tab-pane>
        <el-tab-pane label="返回结果" name="second">
          <div class="api-debug-response-span">
            <span>Status：<span style="color:rgb(23, 179, 163)">{{response.code}}</span> </span>
            <span>Time： <span style="color:rgb(23, 179, 163);margin-left: 10px;">{{response.loadTime}} s</span></span>
            <span>Size：<span style="color:rgb(23, 179, 163);margin-left: 10px;">{{response.size}} B</span></span>
          </div>
          <myEditor v-model="response.responseData" language='dockerfile' title="response"> </myEditor>
        </el-tab-pane>
        <el-tab-pane label="请求Header" name="third">
          <div class="api-debug-response-span">
            <span>Size：<span style="color:rgb(23, 179, 163);margin-left: 10px;">{{response.headerSize}} B</span></span>
          </div>
          <myEditor v-model="response.responseHeader" language='dockerfile' title="response"> </myEditor>
        </el-tab-pane>
      </el-tabs>

    </div>

  </div>
</template>


<script>
import { isEmpty, listToJson } from '@/utils/baseUtil'
import vueJsonEditor from 'vue-json-editor'
import myEditor from '@/components/editor/editor.vue'
export default {
  data () {
    return {

      activeName: 'first',
      activeResponseName: 'second',
      debugLoading: false,

      projectId: null,

      apiForm: {},

      request: {},
      response: {},

      envList: {
        list: [],
        domain: '',
      }

    }
  },
  components: {
    myEditor,
    vueJsonEditor
  },

  methods: {

    //接口调试
    debugApiExecute (apiForm) {
      this.debugLoading = true

      let apiDebugInfo = {}
      this.response = {}
      //初始apiDebugInfo
      apiDebugInfo.id = apiForm.id
      apiDebugInfo.name = apiForm.name
      apiDebugInfo.method = apiForm.method
      apiDebugInfo.protocol = apiForm.protocol
      console.log(this.envList.domain.split(":"))

      if (!isEmpty(this.envList.domain.split(":"))) {
        apiDebugInfo.domain = this.envList.domain.split(":")[0]
        apiDebugInfo.port = this.envList.domain.split(":")[1]
      }
      apiDebugInfo.path = apiForm.path
      apiDebugInfo.postDataType = apiForm.requestBodyType
      apiDebugInfo.httpHeader = listToJson(apiForm.requestHeader)

      if (apiForm.method == 'GET') {
        apiDebugInfo.query = this.listToParams(apiForm.queryParam)
      } else {
        apiDebugInfo.body = listToJson(apiForm.queryParam)
      }

      this.request.url = apiDebugInfo.method + '\n' + apiDebugInfo.protocol + "://" + this.envList.domain + apiDebugInfo.path + '?' + this.listToParams(apiForm.queryParam)
      //发送请求
      this.$http({
        url: this.$http.adornUrl('/aitesting/api/debug'),
        method: 'post',
        data: apiDebugInfo,
      }).then(({ data }) => {
        if (data.code == 0) {
          console.log(data)
          this.response = JSON.parse(JSON.stringify(data.result))
          console.log(this.isJson(this.response.responseData))
          if (this.isJson(this.response.responseData)) {
            let json = this.response.responseData
            this.response.responseData = JSON.stringify(JSON.parse(this.response.responseData), null, 2)
          }

          this.debugLoading = false
          this.$message({ type: 'success', message: data.msg });
        } else {
          this.response = data
          this.debugLoading = false
          this.$message({ type: 'warning', message: data.msg });
        }
      })
      this.debugLoading = false


    },

    //查询环境
    getEnv () {
      this.searchLoading = true
      this.envList.list = []
      this.$http({
        url: this.$http.adornUrl('/aitesting/enviroment/listBy'),
        method: 'get',
        params: {
          'id': '',
          'keyword': '',
          'projectId': this.projectId,
          'pageIndex': 1,
          'pageSize': 1000,
        }
      }).then(({ data }) => {
        if (data.code == 0) {
          this.envList.list = data.page.envs
          console.log(this.envList.list)
        } else {
          this.$message({
            message: data.msg,
            type: 'warning'
          });
        }
      })
    },


    //list转指定格式 & 隔开
    listToParams (paramsList) {
      let params = ""
      if (isEmpty(paramsList)) {
        return params
      }
      let list = paramsList
      for (var i in list) {
        params = params + list[i].name + "=" + list[i].value + "&"
      }
      return params
    },

    //判断是否json
    isJson (str) {
      try {
        JSON.parse(str)
        return true
      } catch (e) {
        return false
      }

    },



    //添加参数
    addNewParams () {
      if (isEmpty(this.apiForm.queryParam)) {
        this.apiForm.queryParam = []
      }
      this.apiForm.queryParam.push({
        name: '',
        value: '',
        remark: '',
        must: true,
      })
    },

    //添加header
    addNewHeaders () {
      if (isEmpty(this.apiForm.requestHeader)) {
        this.apiForm.requestHeader = []
      }
      this.apiForm.requestHeader.push({
        name: '',
        value: '',
        remark: '',
      })
    },

  },


  watch: {
    //获取接口信息
    '$store.state.api.apiInfoForm' () {
      this.apiForm = JSON.parse(JSON.stringify(this.$store.state.api.apiInfoForm))
      console.log(this.apiForm)
    }
  },

  created () {
    this.projectId = this.$store.state.api.projectId
    this.getEnv()
  }
}
</script>

<style scoped>
.api-debug .api-debug-select {
  width: 130px;
}

.api-debug .api-debug-select-1 {
  width: 130px;
  border-left: 1px solid rgb(220, 223, 230);
}

.api-debug >>> .el-input-group__append {
  color: #fff;
  background-color: #17b3a3;
  border-color: #17b3a3;
}

.api-debug .api-tab {
  border: 1px solid rgb(220, 223, 230);
  border-radius: 4px;
  background: rgb(247 247 247 / 67%);
}

.api-debug .interface-tab-in {
  min-height: 200px;
}

.api-debug >>> .el-button--mini.is-circle {
  padding: 7px;
}

.interface-tab-in >>> .el-button--mini {
  margin-bottom: 5px;
}

.api-debug .interface-tab-in .el-col {
  padding-right: 6px;
}

.api-params-type {
  display: block;
  /* text-align: right; */
  padding-bottom: 5px;
  padding-right: 3px;
}

.interface-tab-in {
  margin-left: 5px;
  margin-right: 5px;
  margin-bottom: 5px;
  /* min-height: 200px; */
}

.api-debug .api-debug-request-params {
  margin-top: 15px;
}

.api-debug-response-span {
  float: right;
  font-size: 14px;
  padding-bottom: 5px;
}

.api-debug .interface-tab-in .el-row {
  padding-bottom: 6px;
}
</style>